new Vue({
  el: '#app',
  render: function (createElement) {

    let title = this.$createElement('h2', {
      class: 'config-title',
    }, '页面配置')

    let elTree = createElement('el-tree', {
      props: {
        data: this.data, showCheckbox: "", nodeKey: "id", defaultExpandAll: true, props: this.defaultProps, defaultCheckedKeys: this.checkedKeys
      },
      on: {
        check: this.nodeCheck
      },
      ref: "tree"
    })

    let elScroll = this.$createElement('el-scrollbar', {
      style: { height: "470px" }
    }, [elTree])

    let radioGroup = this.$createElement('el-radio-group', {
      props: { value: this.modeValue },
      on: {
        input: val => this.modeValue = val,
        change: val => this.changeMode(val)
      },
    }, [{ name: '纯净模式', value: '1' }, { name: '经典模式', value: '2' }].map(item => this.$createElement('el-radio',
      {
        props: { label: item.value }
      }
      , item.name)))


    let wrap = createElement('div', null, [title, radioGroup, elScroll])
    return wrap
  },
  data: () => {
    return {
      data: [
        {
          id: 1,
          label: '顶部栏',
          children: [
            { id: 2, label: '图标', path: 'svg.mini-header__logo' },
            { id: 3, label: '左侧菜单', path: 'ul.left-entry' },
            { id: 4, label: '中间搜索', path: 'div.center-search__bar' },
            { id: 5, label: '右侧功能', path: 'ul.right-entry' },
          ]
        },
        {
          id: 10,
          label: '视频标题',
          children: [
            { id: 11, label: '标题', path: '.video-title' },
            { id: 12, label: '播放数据', path: '.video-info-detail' },
          ]
        },
        {
          id: 20,
          label: 'up主信息',
          children: [
            { id: 21, label: '头像', path: 'div.up-info--left' },
            { id: 22, label: '详细信息', path: 'div.up-info--right' },
          ]
        },
        {
          id: 30,
          label: '播放器',
          children: [
            { id: 31, label: '头像关注', path: '.bpx-player-top-left-follow' },
            { id: 32, label: '视频暂停图标', path: '.bpx-player-state-wrap' },
            { id: 33, label: '关闭迷你播放器', path: '.xxx' } // ??
          ]
        },
        {
          id: 40,
          label: '弹幕列表',
          children: [
            { id: 41, label: '弹幕列表', path: '.danmaku-wrap' },
            { id: 42, label: '广告', path: ['#slide_ad', 'a.ad-report'] },
          ]
        },
        {
          id: 50,
          label: '推荐视频',
          children: [
            { id: 51, label: '推荐视频', path: '#reco_list' },
            { id: 52, label: '右侧底部广告', path: '#right-bottom-banner' },
            { id: 53, label: '推荐直播', path: '.pop-live-small-mode' },
          ]
        },
        {
          id: 60,
          label: '发送弹幕',
          children: [
            { id: 61, label: '观看人数', path: '#reco_list', path: ['.bpx-player-video-info-online', '.bpx-player-video-info-divide'] },
            { id: 62, label: '弹幕条数', path: '#reco_list', path: ['.bpx-player-video-info-dm'] },
            { id: 63, label: '发送弹幕', path: '#reco_list', path: '.bpx-player-dm-root' }
          ]
        },
        {
          id: 70,
          label: '投币功能',
          children: [
            { id: 71, label: '投币卡片', path: '#arc_toolbar_report' }
          ]
        },
        {
          id: 80,
          label: '视频简介',
          children: [
            { id: 81, label: '视频简介', path: '#v_desc' }
          ]
        },
        {
          id: 90,
          label: '视频分类tag',
          children: [
            { id: 91, label: '视频分类tag', path: '#v_tag' }
          ]
        },
        {
          id: 100,
          label: '活动卡片',
          children: [
            { id: 101, label: '活动卡片', path: '#activity_vote' },
            { id: 102, label: '广告', path: '#bannerAd' }
          ]
        },
        {
          id: 110,
          label: '评论',
          children: [
            { id: 111, label: '发布评论', path: '.main-reply-box' },
            { id: 112, label: '底部发布评论', path: '.fixed-reply-box' },
            { id: 113, label: '用户等级', path: ['.user-level', '.sub-user-level'] },
            { id: 114, label: '用户头像', path: ['.root-reply-avatar', '.sub-reply-avatar'] },
            { id: 115, label: '所有评论', path: ['#comment'] },
          ]
        },
        {
          id: 120,
          label: '底部右侧悬浮菜单',
          children: [
            { id: 121, label: '小窗客服', path: ['.mini-player-window', 'a[title="帮助反馈"]'] },
            { id: 122, label: '新旧版切换', path: '.fixed-nav' },
          ]
        },
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      checkedKeys: [],
      modeValue: '1',   // 当前模式
      modeData: {       // 模式的选中数据
        '1': [],
        '2': [3, 4, 10, 11, 12, 30, 31, 32, 33, 41, 60, 61, 62, 63, 111, 113, 114, 115]
      }
    }
  },
  computed: {
    allTreeLeafArray() {
      return this.data.map(item => item.children.map(child => { return { path: child.path, id: child.id } })).flat()
    }
  },
  created() {
    chrome.storage.sync.set({ treeData: this.data })
    chrome.storage.sync.get("checkedKeys", (res) => {
      this.checkedKeys = res.checkedKeys || []
    })
    chrome.storage.sync.get("mode", (res) => {
      this.modeValue = res.mode || '1'
    })
  },
  mounted() {

  },
  methods: {
    async nodeCheck(currentNode, treeNode) {
      let h3 = document.querySelectorAll('h3')

      let queryOptions = { active: true, currentWindow: true };
      // `tab` will either be a `tabs.Tab` instance or `undefined`.
      let [tab] = await chrome.tabs.query(queryOptions);

      let ids = [currentNode.id]
      let paths = currentNode.path ? [currentNode.path] : []
      if (currentNode.children) {
        ids.push(...currentNode.children.map(item => item.id))
        paths.push(...currentNode.children.map(item => item.path))
      }

      chrome.storage.sync.set({ currentClickedIds: ids, currentClickedPaths: paths, checkedNodes: treeNode.checkedNodes, checkedKeys: treeNode.checkedKeys })

      chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: this.settingSingle(),
        args: []
      })

    },
    settingSingle() {
      return async () => {
        let { currentClickedIds } = await chrome.storage.sync.get("currentClickedIds")
        let { currentClickedPaths } = await chrome.storage.sync.get("currentClickedPaths")
        let { checkedKeys } = await chrome.storage.sync.get("checkedKeys")

        let hiddenFlag = true

        // 当前点击的，不在checkedKeys里面，未选中,不显示
        if (checkedKeys.indexOf(currentClickedIds[0]) === -1) {
          hiddenFlag = true
        } else {
          // 当前点击的，在checkedKeys里面，选中操作
          hiddenFlag = false
        }





        // 检查当前点击的id，筛选出未选中的id
        // 未选中 -> display none
        // 选中   -> display unset 或 无操作
        let selector = currentClickedPaths

        selector.forEach(sec => {
          let htmlColl = document.querySelectorAll(sec)

          Array.from(htmlColl).forEach(item => {
            if (hiddenFlag) {
              item.classList.add('biliHidden')
            } else {
              item.classList.remove('biliHidden')
            }
          })
        })
      }
    },
    async changeMode(val) {
      console.log('changeMode 11', this.$refs.tree)
      // 取选中的checkedKeys
      let keys = this.modeData[val]

      chrome.storage.sync.set({
        mode: val
      })

      this.$refs.tree.setCheckedKeys(keys)
      // 获取选中的node
      let checkedNodes = this.$refs.tree.getCheckedNodes(true)
      let checkedKeys = this.$refs.tree.getCheckedKeys(true)

      chrome.storage.sync.set({
        checkedNodes: checkedNodes,
        checkedKeys: checkedKeys
      })


      let checkPaths = []
      let unCheckPaths = []

      this.allTreeLeafArray.filter(treeLeaf => {
        if (!checkedKeys.includes(treeLeaf.id)) {
          unCheckPaths.push(treeLeaf.path)
        } else {
          checkPaths.push(treeLeaf.path)
        }
      })

      let queryOptions = { active: true, currentWindow: true };
      // `tab` will either be a `tabs.Tab` instance or `undefined`.
      let [tab] = await chrome.tabs.query(queryOptions);

      chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: (checkPaths, unCheckPaths) => {
          checkPaths.forEach(path => {
            document.querySelectorAll(path).forEach(coll => {
              coll.classList.remove('biliHidden')
            })
          })
          unCheckPaths.forEach(path => {
            document.querySelectorAll(path).forEach(coll => {
              coll.classList.add('biliHidden')
            })
          })
        },
        args: [checkPaths, unCheckPaths]
      })

    }
  }
})